package com.tg.service;

import com.alibaba.fastjson.JSONObject;
import com.tg.clients.TicketClients;
import com.tg.clients.UserClients;
import com.tg.dao.OrderDetailRepository;
import com.tg.dao.OrderMapper;
import com.tg.dao.OrderRepository;
import com.tg.dao.SeatRepository;
import com.tg.pojo.entity.*;
import com.tg.pojo.requestVo.OrderReq;
import com.tg.pojo.requestVo.UserReq;
import com.tg.pojo.resposeVo.BaseResp;
import com.tg.pojo.resposeVo.PayResp;
import com.tg.util.GenerateOrderNum;
import com.tg.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * @Author 王兴
 * @Description
 * @Date 2022/3/28
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    OrderDetailRepository orderDetailRepository;

    @Autowired
    SeatRepository seatRepository;

    @Resource
    OrderMapper orderMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserClients userClients;

    @Autowired
    TicketClients ticketClients;

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public BaseResp addOrder(OrderReq orderReq, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userid = jwtUtils.verfiy(token);
        Integer ticketId = orderReq.getTicketId();
        String seatType = orderReq.getSeatType();
        List<UserReq> userReqList = orderReq.getUserReqList();
        TgOrder tgOrder = new TgOrder();
        String orderId = new GenerateOrderNum().generate("");
        tgOrder.setOrderStatus(1);
        tgOrder.setTicketId(ticketId);
        tgOrder.setOrderId(orderId);
        tgOrder.setIfdelete(0);
        tgOrder.setCreateTime(new Date());
        tgOrder.setUpdateTime(new Date());
        tgOrder.setUserId(userid);
        TgOrderDetail orderDetail = new TgOrderDetail();
        Double total = 0.0;
        for (UserReq userReq : userReqList) {
            Integer userid1 = userReq.getUserid();
            Integer typeId = userReq.getTypeId();
            BaseResp byId = ticketClients.findById(ticketId);
            Object data = byId.getData();
            String s = JSONObject.toJSONString(data);
            Ticket ticket = JSONObject.parseObject(s, Ticket.class);
            TrainMessage message = ticket.getMessage();
            Double price = 0.0;
            if (typeId == 0) {
                //价格比对通过，生成总订单号
                orderDetail.setSeatType("特等座");
                price = message.getSuperSeatPrice();
                total += price;
            } else if (typeId == 1) {
                //价格比对通过，生成总订单号
                orderDetail.setSeatType("一等座");
                price = message.getFirstSeatPrice();
                total += price;
            } else if (typeId == 2) {
                //价格比对通过，生成总订单号
                orderDetail.setSeatType("二等座");
                price = message.getSecondSeatPrice();
                total += price;
            } else if (typeId == 3) {
                //价格比对通过，生成总订单号
                orderDetail.setSeatType("无座");
                price = message.getSecondSeatPrice();
                total += price;
            }
            List<TgSeat> seatNumber = seatRepository.findSeatNumberByTicketIdAndSeatTypeNumberAndSeatStatus(ticketId, typeId, 0);
            List list = new ArrayList();
            String seatNumber2 = null;
            if (seatNumber.size() > 0) {
                for (TgSeat tgSeat : seatNumber) {

                    String seatNumber1 = tgSeat.getSeatNumber();
                    if (seatNumber1.contains(seatType)) {
                        list.add(seatNumber1);
                    }
                }
                int size = list.size();
                Random random = new Random();
                int i = random.nextInt(size);
                seatNumber2 = list.get(i).toString();

                TgSeat tgSeat = seatRepository.findSeatStatusByTicketIdAndSeatNumber(ticketId, seatNumber2);
                tgSeat.setSeatStatus(1);
                seatRepository.save(tgSeat);
            } else {
                Random random = new Random();
                int i = random.nextInt(3);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(i + 1);
                stringBuffer.append("车");
                seatNumber2 = stringBuffer.toString();
            }

            String orderdetailId = new GenerateOrderNum().generate("");
            orderDetail.setPassengerId(userid1);
            orderDetail.setOrderId(orderId);
            orderDetail.setCreateTime(new Date());
            orderDetail.setIfdelete(0);
            orderDetail.setOrderDetailId(orderdetailId);
            orderDetail.setUpdateTime(new Date());
            orderDetail.setSeatNumber(seatNumber2);
            orderDetail.setPrice(price);
            orderDetailRepository.save(orderDetail);
        }

        tgOrder.setOrderPrice(total);
        orderRepository.save(tgOrder);
        return new BaseResp(1, "添加成功", null, null);
    }

    @Override
    public BaseResp findOrderByUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userid = jwtUtils.verfiy(token);
        List<TgOrderVo> details = orderMapper.findOrderAndOrderDetailsByUserId(userid, 1);
        for (TgOrderVo detail : details) {
            Integer ticketId = detail.getTicketId();
            BaseResp byId = ticketClients.findById(ticketId);
            Object data = byId.getData();
            String s = JSONObject.toJSONString(data);
            Ticket ticket = JSONObject.parseObject(s, Ticket.class);
            detail.setTicket(ticket);
        }
        return new BaseResp(1, "查询成功", details, null);
    }

    @Override
    public BaseResp cancelOrder(Map map) {
        String orderId = map.get("orderId").toString();
        Optional<TgOrder> byId = orderRepository.findById(orderId);
        if (!byId.isPresent()) {
            return new BaseResp(0, "此条订单不存在", null, null);
        }
        TgOrder tgOrder = byId.get();
        tgOrder.setOrderStatus(4);
        orderRepository.save(tgOrder);

        return new BaseResp(1, "订单已取消", null, null);
    }

    @Override
    public BaseResp findDetailByOrderid(String orderId) {
        List<TgOrderDetail> detailByOrderid = orderDetailRepository.findDetailByOrderId(orderId);
        if (detailByOrderid == null || detailByOrderid.size() <= 0) {
            return new BaseResp(0, "订单不存在，或已经失效", null, null);
        }
        return new BaseResp(1, "查询成功", detailByOrderid, null);
    }

    @Override
    public BaseResp findByOrderid(String orderId) {

        Optional<TgOrder> byId = orderRepository.findById(orderId);

       if(!byId.isPresent()){
           return new BaseResp(0, "查询失败", null, null);
       }
        return new BaseResp(1, "查询成功", byId.get(), null);
    }

    @Override
    public BaseResp updateStatus(String orderId, Integer status) {
        Optional<TgOrder> byId = orderRepository.findById(orderId);
        if (!byId.isPresent()) {
            return new BaseResp(0, "订单不存在，或已经失效", null, null);
        }
        TgOrder tgOrder = byId.get();
        tgOrder.setOrderStatus(status);
        orderRepository.save(tgOrder);
        return new BaseResp(1, "更改成功", null, null);
    }

    @Override
    public BaseResp findByStatusAndUserid(Map map) {
        Integer status = Integer.valueOf(map.get("orderStatus").toString());
        Integer userid = Integer.valueOf(map.get("userid").toString());
        //String token = request.getHeader("token");
        //Integer userid = jwtUtils.verfiy(token);
        List<TgOrderVo> detailsByUserId = orderMapper.findOrderAndOrderDetailsByUserId(userid, status);
        if (detailsByUserId == null || detailsByUserId.size() <= 0) {
            return new BaseResp(0, "暂无订单", null, null);
        }
        for (TgOrderVo detail : detailsByUserId) {
            Integer ticketId = detail.getTicketId();
            BaseResp byId = ticketClients.findById(ticketId);
            Object data = byId.getData();
            String s = JSONObject.toJSONString(data);
            Ticket ticket = JSONObject.parseObject(s, Ticket.class);
            detail.setTicket(ticket);
        }
        return new BaseResp(1, "查询成功", detailsByUserId, null);
    }

    @Override
    public BaseResp saveAndFlush(TgOrder tgOrder) {
        orderMapper.add(tgOrder);

        return new BaseResp(1, "添加成功~", null, null);
    }

    @Override
    public BaseResp findByDetailByOrderDetail(String detailId) {
        TgOrderDetail detailByOrderDetailId = orderDetailRepository.findDetailByOrderDetailId(detailId);
        if (detailByOrderDetailId != null) {
            return new BaseResp(1, "查询成功", detailByOrderDetailId, null);
        }
        return new BaseResp(0, "查询失败", null, null);
    }

    @Override
    public BaseResp delById(String oldOrderId) {
        orderRepository.deleteById(oldOrderId);

        return new BaseResp(0, "删除成功！", null, null);
    }

    @Override
    public BaseResp updateOrderId(TgOrderDetail tgOrderDetail) {

        orderMapper.updateOrderId(tgOrderDetail);

        return new BaseResp(0, "更新成功！！", null, null);
    }
}
